package com.example.com.common.utils;

import android.text.TextUtils;

import java.io.FileInputStream;

/**
 * Created by qingning on 2016/3/17.
 */
public class FileTypeUtil {
    public static final int UNKNOW = 0;//未知
    public static final int JPG = 1;
    public static final int PNG = 2;
    public static final int GIF = 3;
    public static final int BMP = 4;
    public static final int WEBP = 5;//此种格式是谷歌提出来新格式，一般安卓手机网页上保存下来的图片格式是这种，目前ios还不支持
    //获取文件头信息
    private static String getFileHeader(String filePath) {
        FileInputStream is = null;
        String value = null;
        try {
            is = new FileInputStream(filePath);
            byte[] b = new byte[3];
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
        } catch (Exception e) {
        } finally {
            if(null != is) {
                try {
                    is.close();
                } catch (Exception e) {

                }
            }
        }
        System.out.println("header:"+value);
        return value;
    }
    private static String bytesToHexString(byte[] src){
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (int i = 0; i < src.length; i++) {
            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }
        return builder.toString();
    }
    //获取图片格式
    public static int getImagesFormat(String filePath){
        String fileHeader = getFileHeader(filePath);
        if(!TextUtils.isEmpty(fileHeader)){
            if(fileHeader.startsWith("FFD8FF")){
                return JPG;
            }else if(fileHeader.startsWith("89504E")){
                return PNG;
            }else if(fileHeader.startsWith("474946")){
                return GIF;
            }else if(fileHeader.startsWith("424D")){
                return BMP;
            }else if(fileHeader.startsWith("524946")){
                return WEBP;
            }
        }
        return UNKNOW;
    }
}
